package com.example.petshopping.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.LayoutRes;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.petshopping.R;
import com.example.petshopping.model.Product;

import java.util.List;

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {

    private final Context context;
    private final List<Product> products;
    private OnProductClickListener listener;
    private final int itemLayoutRes;

    public ProductAdapter(Context context, List<Product> products) {
        this(context, products, R.layout.item_product_list);
    }

    public ProductAdapter(Context context, List<Product> products, @LayoutRes int itemLayoutRes) {
        this.context = context;
        this.products = products;
        this.itemLayoutRes = itemLayoutRes;
    }

    public interface OnProductClickListener {
        void onProductClick(Product product, int position);
        void onDeleteClick(Product product, int position);
    }

    public void setOnProductClickListener(OnProductClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(itemLayoutRes, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Product product = products.get(position);
        
        // 设置商品数据
        holder.titleView.setText(product.getName());
        holder.priceView.setText(product.getPrice());
        
        // 处理图片资源 - 使用新的imageUrl逻辑
        setProductImage(holder.imageView, product.getImageUrl());
        
        // 显示拍卖时间和卖家信息
        if (product.getAuctionEndTime() != null && !product.getAuctionEndTime().isEmpty()) {
            holder.timeView.setVisibility(View.VISIBLE);
            holder.timeView.setText(product.getAuctionEndTime());
        }
        if (product.getSellerName() != null && !product.getSellerName().isEmpty()) {
            holder.sellerView.setVisibility(View.VISIBLE);
            holder.sellerAvatarView.setVisibility(View.VISIBLE);
            holder.sellerView.setText(product.getSellerName());
        }
        if (product.getSellerAvatar() != null && !product.getSellerAvatar().isEmpty()) {
            if (product.getSellerAvatar().startsWith("http")) {
                Glide.with(context)
                        .load(product.getSellerAvatar())
                        .apply(new RequestOptions()
                                .placeholder(R.drawable.default_avatar)
                                .error(R.drawable.default_avatar)
                                .circleCrop()) // 圆形头像
                        .into(holder.sellerAvatarView);
            }
        }
        
        // 设置标签（无理由退货）
        TextView tagView = holder.itemView.findViewById(R.id.product_tag);
        if (tagView != null) {
            tagView.setText("无理由");
            tagView.setVisibility(View.VISIBLE);
        }
        
        // 移除收藏按钮相关功能
        holder.favoriteView.setVisibility(View.GONE);
        
        // 显示精品标签
        // if (product.isPromoted()) {
        //     holder.promotedView.setVisibility(View.VISIBLE);
        // } else {
        //     holder.promotedView.setVisibility(View.GONE);
        // }
        // 移除精品标签
        holder.promotedView.setVisibility(View.GONE);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onProductClick(product, holder.getAdapterPosition());
            }
        });
        
        holder.deleteView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onDeleteClick(product, holder.getAdapterPosition());
            }
        });
    }
    
    // 处理图片资源的方法
    private void setProductImage(ImageView imageView, String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            // 如果没有图片URL，使用默认图片
            imageView.setImageResource(R.drawable.cat);
            return;
        }

        // 判断是网络URL还是本地资源名称
        if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
            // 网络图片URL，使用Glide加载
            Glide.with(context)
                    .load(imageUrl)
                    .apply(new RequestOptions()
                            .placeholder(R.drawable.cat)        // 加载中显示的占位图
                            .error(R.drawable.cat)              // 加载失败显示的图片
                            .diskCacheStrategy(DiskCacheStrategy.ALL) // 缓存策略
                            .centerCrop())                      // 图片缩放方式
                    .into(imageView);
        }
    }

    @Override
    public int getItemCount() {
        return products.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView titleView;
        TextView priceView;
        TextView timeView;
        TextView sellerView;
        ImageView sellerAvatarView;
        ImageView favoriteView;
        ImageView deleteView;
        View promotedView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.product_image);
            titleView = itemView.findViewById(R.id.product_title);
            priceView = itemView.findViewById(R.id.product_price);
            timeView = itemView.findViewById(R.id.product_time);
            sellerView = itemView.findViewById(R.id.seller_name);
            sellerAvatarView = itemView.findViewById(R.id.seller_avatar);
            favoriteView = itemView.findViewById(R.id.favorite_button);
            deleteView = itemView.findViewById(R.id.delete_button);
            promotedView = itemView.findViewById(R.id.product_badge);
        }
    }
} 